package http

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// 响应数据体
type ResponseEntity struct {
	// 错误码
	ErrorCode int `json:"errcode"`
	// 响应消息
	Message string `json:"errmsg"`
	// 响应数据
	Data interface{} `json:"data"`
}

type Response struct {
	ctx *gin.Context
}

func NewResponse(ctx *gin.Context) Response {
	return Response{
		ctx: ctx,
	}
}

// 响应成功请求
func (r Response) Success(data interface{}, msg string) {
	if len(msg) == 0 {
		msg = "success"
	}

	// 响应数据
	r.ctx.JSON(http.StatusOK, ResponseEntity{
		ErrorCode: 0,
		Message:   msg,
		Data:      data,
	})
	return
}

func (r Response) DefaultSuccess(data interface{}) {
	r.Success(data, "成功")
}

func (r Response) ErrorData(err error, data interface{}) {
	if err == nil {
		return
	}

	r.ctx.JSON(http.StatusOK, ResponseEntity{
		ErrorCode: http.StatusInternalServerError,
		Message:   err.Error(),
		Data:      data,
	})
	return

	return
}

// 响应错误
func (r Response) Error(err error) {
	r.ErrorData(err, nil)
}
